package com.test.mchelepesa.adapter_rice;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.mchelepesa.bean_rice.config_info_rice.AppShowInfo_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.ThreadUtil_rice;
import com.test.mchelepesa.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class WalletAccountTypeListAdapter_Cote_rice extends BaseAdapter {

    private final LayoutInflater inflater;
    private final ArrayList<AppShowInfo_rice.WalletChannel> walletChannels;

    public WalletAccountTypeListAdapter_Cote_rice(Context context) {
        inflater = LayoutInflater.from(context);
        this.walletChannels = AppShowInfo_rice.getInstance().getWalletChannels();
    }

    @Override
    public int getCount() {
        return walletChannels.size();
    }

    @Override
    public AppShowInfo_rice.WalletChannel getItem(int i) {
        return walletChannels.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SuppressLint("ViewHolder")
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        view = inflater.inflate(R.layout.item_wallet_account_type_cote_rice,viewGroup,false);

        AppShowInfo_rice.WalletChannel walletChannel = walletChannels.get(i);

        ImageView accountTypeIv = view.findViewById(R.id.item_wallet_account_type_iv_account_type);
        TextView accountTypeTv = view.findViewById(R.id.item_wallet_account_type_tv_account_type);

        accountTypeTv.setText(walletChannel.getDesc());

        try {
            if (!TextUtils.isEmpty(walletChannel.getLogo())){
                URL url = new URL(walletChannel.getLogo());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    if (bitmap!=null){
                        ThreadUtil_rice.getInstance().runOnUiThread(() -> {
                            if (accountTypeIv!=null) accountTypeIv.setImageBitmap(bitmap);
                        });
                    }
                }
            }
        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }

        return view;
    }

}
